class Login{
    constructor(container){
        this.container=container;
        this.creatDOM().then($.proxy(this.init,this));
    }
    creatDOM(){
        return new Promise(resolve=>{
            this.container.load("/html/component/common/login.html",resolve);
        }
        );
    }
    init(){
    this.userInput = $("#loginUserInput");
    this.pwdInput = $("#loginPwdInput");
    this.btn = $("#login-btn");
    this.succ = $("#login-succ");
    this.fail = $("#login-fail");
    this.closeBtn = $("#login-close");

    this.unloginUl = $("#unlogin-ul");
    this.loginUl = $("#login-ul");
    this.userSpan = $("#user-span");
    this.logoutBtn = $("#logout-btn");

    this.BindEvents();
    this.getLoginState();
  }

  BindEvents () {
    this.btn.on("click", $.proxy(this.handleLoginClick, this));
    this.logoutBtn.on("click", $.proxy(this.logoutBtnClick, this));
  }

  handleLoginClick () {
    let username = this.userInput.val(),
      password = this.pwdInput.val();
    
    //发送ajax登录
    $.post(baseUrl + "/user/login", {username, password}, $.proxy(this.handleLoginSucc, this));
  }

  handleLoginSucc (res) {
    if(res.res_code === 1){

      this.getLoginState();

     
    }else{
      //登录失败
      this.fail.removeClass("hide");
      setTimeout(() => {
        this.fail.addClass("hide");
        
      }, 1000);
    }
  }
  // 获取登录状态
  getLoginState () {
    $.post(baseUrl+"/user/isLogin", $.proxy(this.handelIsLoginSucc, this));
  }

  handelIsLoginSucc (res) {
    if(res.res_code === 1){
       // 登录成功
       this.succ.removeClass("hide");
       setTimeout(() => {
         this.succ.addClass("hide");
         this.closeBtn.trigger(new $.Event("click"));
         
         this.unloginUl.addClass("hide");
         //用户名
         this.userSpan.html(res.res_body.username);
 
         this.loginUl.removeClass("hide");

       }, 1000);
     
    }
  }

  logoutBtnClick () {
    $.get("/user/logout", $.proxy(this.logoutSucc, this));
  }

  logoutSucc (res) {
    if(res.res_code === 1){
      //成功退出登录
      alert(res.res_message);
      this.unloginUl.removeClass("hide");
 
      this.loginUl.addClass("hide");
    }
  }
}